'''
Description: 测试
Author: 天涯过客
Date: 2025-05-13 16:48:47
'''
import sys
sys.path.append("D:\\workbench\\py\\compile\\src")
from lexer import run_lexer
from parser import run_parser
from Semantic import run_semantic_analysis
from middleCode import run_generate_code


def get_tokens(code):
    """
    词法分析
    :param code: 源代码
    :return: 词法单元列表
    """
    tokens, errors = run_lexer(code)
    return tokens,errors


def get_syntax_tree(tokens):
    """
    语法分析
    :param tokens: 词法单元列表
    :return: 语法树
    """
    syntax_tree = run_parser(tokens)
    return syntax_tree

def get_symbol_table(syntax_tree):
    """
    语义分析
    :param syntax_tree: 语法树
    :return: 符号表
    """
    symbol_table,errors  = run_semantic_analysis(syntax_tree)
    return symbol_table,errors


def get_intermediate_code(syntax_tree):
    """
    中间代码生成
    :param syntax_tree: 语法树
    :return: 中间代码
    """
    quads = run_generate_code(syntax_tree)
    return quads

def test_semantic_analysis():
    """
    测试语义分析
    :return: None
    """
    tokens,_ = get_tokens(code)
    syntax_tree = get_syntax_tree(tokens)
    print(syntax_tree)
    symbol_table,errors = get_symbol_table(syntax_tree)
    if errors:
        print("语义分析错误：")
        for error in errors:
            print(error)
        
    else:
        print("语义分析成功！")
    print("符号表：")
    print(symbol_table)

code = """
//算术表达式
int main() {
       int x, y, z;
       x = 9;
       y = 3;
       z = x - y * y - x % 3;
       write(x);
       write(y);
       write(z);
       }
"""

def main():
    test_semantic_analysis()

if __name__ == "__main__":
    main()